<?php

App::uses('AppModel', 'Model');
App::uses('CompositeKeyModel', 'Model');

/**
 * MemberAccountSession Model
 *
 * @property MemberAccount $MemberAccount
 */
class MemberAccountSession extends CompositeKeyModel {


    public $useDbConfig = "organisations";

    /**
     * belongsTo associations
     *
     * @var array
     */
    public $belongsTo = array(
        'MemberAccount' => array(
            'className' => 'MemberAccount',
            'foreignKey' => 'member_account_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );
    
    /**
     * Validates a member account session to determine if the session for the device is still active
     * 
     * @param int $member_account_id
     * @param mixed $session_id
     * @return array
     */
    public function validate($member_account_id, $session_id) {
        $data = $this->find('first', array(
            'contain' => array(
                'MemberAccount' => array(
                    'fields' => array('id', 'username', 'last_login', 'member_id','timezone'),
                    'Member'
                )
            ),
            'conditions' => array(
                'member_account_id' => $member_account_id,
                'session_device_id' => $session_id,
                'session_expiry_dt > now()',
                'MemberAccountSession.active' => 1
            )
        ));
        
        if( $data ) {
            // restructure for presentation
            $data['Member'] = $data['MemberAccount']['Member'];
            
            unset($data['MemberAccountSession']);
            unset($data['MemberAccount']['Member']);
            
            return array('status' => 'success', 'session_status' => 'valid', 'account' => $data);
        }
        
        return array('status' => 'success', 'session_status' => 'invalid');
    }
    
    /**
     * 
     * @param int $member_account_id
     * @param boolean $remember_me
     * @return array
     */
    public function start($member_account_id, $remember_me = false) {
        
        $session_start_dt = new DateTime();

        $session_expiry_dt = new DateTime();
        $session_expiry_dt->add( new DateInterval("PT2H") );

        if( $remember_me ) {
            $session_expiry_dt->add( new DateInterval("P14D") );
        }
        
        $data = array(
            'member_account_id' => $member_account_id,
            'session_start_dt' => $session_start_dt->format('Y-m-d H:i:s'),
            'session_expiry_dt' => $session_expiry_dt->format('Y-m-d H:i:s'),
            'session_last_ip' => isset($_POST['REMOTE_ADDR']) ? $_POST['REMOTE_ADDR'] : $_SERVER['REMOTE_ADDR'],
            'session_device_id' => isset($_POST['HTTP_USER_AGENT']) ? md5($_POST['HTTP_USER_AGENT']) : md5($_SERVER['HTTP_USER_AGENT']),
            'session_user_agent' => isset($_POST['HTTP_USER_AGENT']) ? $_POST['HTTP_USER_AGENT'] : $_SERVER['HTTP_USER_AGENT']
        );
        
        $existing = $this->find('first', array(
            'conditions' => array(
                'member_account_id' => $member_account_id,
                'session_device_id' => $data['session_device_id'],
                'session_expiry_dt > now()', // should not have expired
                'active' => 1 // must be active
            ),
            'recursive' => -1
        ));

        if( $existing ) {
            $data = array_merge($existing['MemberAccountSession'], $data);
        }
        
        $session = $this->save($data);

        return $session['MemberAccountSession'];
    }
    
    /**
     * Ends an active session for a specific member account
     * 
     * @param int $member_account_id
     * @param mixed $session_id
     * 
     * @return array
     */
    public function end($member_account_id, $session_id) {

        $existing = $this->find('first', array(
            'conditions' => array(
                'member_account_id' => $member_account_id,
                'session_device_id' => $session_id,
                'session_expiry_dt > now()' // must be active
            ),
            'recursive' => -1
        ));
        
        if( $existing ) {
            $existing['MemberAccountSession']['active'] = 0;
            
            $this->save($existing);
            
            return array('status' => 'success', 'message' => 'Session ended successfully.');
        }
        
        return array('status' => 'failed', 'message' => 'Session information not found.');
    }
}
